# cocoa bridge
from Foundation import *
from AppKit import *
from ScriptingBridge import SBApplication
from objc import ivar

# standard modules
import os
from time import sleep

from helpers import log

class TCArrayController(NSArrayController):
	"""
	A slightly modified array controller, mainly for
	the purpose of syncing with the QuickLook panel
	and autosaving data upon selection changes
	"""
	qlIndex = ivar("qlIndex")
	qlPanel = ivar("qlPanel")
	throbber = ivar("throbber")
	tableView = ivar("tableView")
	
	def awakeFromNib(self):
		log("i am the TC array controller!")
		self.setSortDescriptors_(
			[NSSortDescriptor.alloc().initWithKey_ascending_selector_("name", True, "caseInsensitiveCompare:")])
		return super(self.__class__, self).awakeFromNib()
	
	def setArrangedObjects_(self, objs):
		log("set arranged objects")
		super(self.__class__, self).setArrangedObjects_(objs)
		self.objectsChanged()
	
	def saveAll(self):
		if self.throbber is not None:
			self.throbber.startAnimation_(self)
		try:
			for f in self.selectedObjects():
				log(f)
				f.save()
		except Exception,e:
			log("saveAll error: ",e)
		
		if self.throbber is not None:
			self.throbber.stopAnimation_(self)
	
	def qlIndexChanged_(self, index):
		log("ql index changed to ",index)
		self.setSelectionIndex_(index)
	
	def setQLIndex(self, index):
		"""Set the quickLook panel to show the given index"""
		self.qlIndex = index
		if (not self.qlPanel is None) and self.qlPanel.isOpen():
			self.qlPanel.setIndexOfCurrentURL_(index)
		
	def inSync(self):
		"""returns False iff the QLPanel and the current selection are out of sync"""
		return (self.qlIndex is None) or (not self.qlIndex.isOpen()) or (self.qlIndex.indexOfCurrentURL() == self.qlIndex)
		
	def setSelectionIndex_(self,i):
		self.saveAll()
		self.setQLIndex(i)
		return super(self.__class__,self).setSelectionIndex_(i)
	
	def selectNext_(self, sender):
		if not self.canSelectNext():
			return
		self.setQLIndex(self.selectionIndex()+1)
		super(self.__class__, self).selectNext_(sender)
		

	def selectPrevious_(self, sender):
		if not self.canSelectPrevious():
			return
		self.setQLIndex(self.selectionIndex()-1)
		super(self.__class__, self).selectPrevious_(sender)
		
		
	def setSelectionIndexes_(self,i):
		self.saveAll()
		try:
			index = i.firstIndex()
			self.setQLIndex(index)
		except:
			pass
		return super(self.__class__,self).setSelectionIndexes_(i)
		
	def setSelectedObjects_(self,sel):
		self.saveAll()
		res = super(self.__class__,self).setSelectedObjects_(sel)
		self.setQLIndex(self.selection())
	
	def setContent_(self,x):
		self.saveAll()
		return super(self.__class__,self).setContent_(x)
	
	def setContentArray_(self, arr):
		self.saveAll()
		return super(self.__class__,self).setContentArray_(arr)
	
	def setSortDescriptors_(self,descriptors):
		log(descriptors)
		ret = super(self.__class__,self).setSortDescriptors_(descriptors)
		self.objectsChanged()
		return ret

	def tableView_writeRowsWithIndexes_toPasteboard_(self, view, indexes, pBoard):
		log("drag start!")
		items = []
		i = indexes.firstIndex()
		while i != NSNotFound:
			try:
				items.append(self.arrangedObjects()[i])
			except Exception:
				pass
			i = indexes.indexGreaterThanIndex_(i)
		
		data = [x.path for x in items]
		pBoard.declareTypes_owner_(NSArray.arrayWithObject_(NSFilenamesPboardType), self)
		pBoard.setData_forType_(data, NSFilenamesPboardType)
		
		self.tableView.setDraggingSourceOperationMask_forLocal_(NSDragOperationEvery, False)
		return True

	def tableView_validateDrop_proposedRow_proposedDropOperation_(self, view, drop, row, operation):
		log("drag validation..")
		return NSDragOperationEvery
	
	def objectsChanged(self):
		self.saveAll()
		if (not self.qlPanel is None) and self.qlPanel.isOpen():
			index = 0
			newIndex = self.selectionIndex()
			if newIndex is not NSNotFound:
				index = newIndex
			self.qlPanel.setURLs_currentIndex_preservingDisplayState_([x.url for x in self.arrangedObjects()], index, True)
